<?php

class Cartoon extends CI_Controller{
	public function __construct(){
		parent::__construct();
	}
	
	public function index(){
		$this->load->Model("mimage");
		if(isset($_POST)){
			session_start();
			$userId = "";
			$imageName = "";
			if(isset($_SESSION["userId"]))
				$userId = $_SESSION["userId"];
			else 
				redirect($this->config->item["RedirectURL"]);
			if(isset($_SESSION["imageName"])){
				$imageName = $_SESSION["imageName"];
				$dotPos = strpos ( $imageName, "." );
				$extension = substr ( $imageName, $dotPos, strlen ( $imageName ) );
				if (strcmp ( $extension, ".png" ) == 0) {
					$this->session->set_flashdata ( "Error", "Please use jpeg or jpg extension photo" );
					redirect ( base_url ( "index.php/ImageUpload/ImageUpload/index" ) );
					return;
				}
			}else {
				$_SESSION["imageName"] = "default.jpg";
				$imageName = $_SESSION["imageName"];
				//copy default image to userId folder
				$folderName = $userId;
				$destination = './UserUploads/' . $folderName;
				$mode = 0777;
				$mkdirError = ! is_dir ( $destination ) ? mkdir ( $destination, $mode ) : true;
				if (! $mkdirError) {
					$this->session->set_flashdata ( "Error", "There is an error with server" );
					redirect ( base_url ( "index.php/ImageUpload/ImageUpload/index" ) );
					return;
				}
				
				$copyFile = copy("./UserUploads/default.jpg", $destination."/default.jpg");
				if(!$copyFile){
					$this->session->set_flashdata ( "Error", "There is an error with server" );
					redirect ( base_url ( "index.php/ImageUpload/ImageUpload/index" ) );
					return;
				}
			}
			$this->mimage->makeCartoon();
		}
		if(isset($_SESSION["imagePath"]))
			$size = $this->mimage->getSize($_SESSION["imagePath"]);
		else 
			$size = $this->mimage->getSize("./UserUploads/$userId/default.jpg");
		$data = array('funcType'=>3, 'width'=>$size[0], 'height' => $size[1], 'userId'=>$userId, 'imageName'=>$imageName);
		$this->load->view("FunctionTemplate/index", $data);
	}
}